package com.citcc.api.netty.server;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.logging.LoggingHandler;
import org.jboss.netty.handler.timeout.IdleStateHandler;
import org.jboss.netty.logging.InternalLogLevel;
import org.jboss.netty.util.HashedWheelTimer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.citcc.api.netty.handle.HeartBeatHandler;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

/**
 * @author liyachong
 * @date 2019/4/4
 * @time 10:27
 */
@Component
public class TcpServer implements CommandLineRunner {
    private Logger log = LoggerFactory.getLogger(TcpServer.class);

    @Value("${citccIot.tcpPort}")
    private int port;

    public void bind() throws Exception {
        ChannelFactory factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
                Executors.newCachedThreadPool());
        ServerBootstrap bootstrap = new ServerBootstrap(factory);
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() {
                ChannelPipeline pipeline = Channels.pipeline();
                pipeline.addLast("loging", new LoggingHandler(InternalLogLevel.INFO));
                //设置特殊分隔符
                //ChannelBuffer buf  =  ChannelBuffers.copiedBuffer("5d".getBytes());
                //pipeline.addLast("decoder", new Decoder2(200, false, true,buf));
                pipeline.addLast("decoder", new ConsuDecoder());
                pipeline.addLast("encoder", new ConsuEncoder());
                //pipeline.addLast("idlehandler", new IdleStateHandler(new HashedWheelTimer(), 180, 0 , 0));
                //pipeline.addLast("hearbeat", new HeartBeatHandler());
                pipeline.addLast("serverHandler", new ServerHandler());

                return pipeline;
            }
        });

        bootstrap.setOption("child.tcpNoDelay", true);
        bootstrap.setOption("child.keepAlive", true);

        bootstrap.bind(new InetSocketAddress(port));
        log.info("TCP服务启动完毕,port=[{}}", port);
        System.out.println("JTServer startup ....");
    }

    @Override
    public void run(String... args) throws Exception {
        bind();//系统自动启动类
    }

}
